package com.antdesignbackend.backend.common.http;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.util.Map;

/**
 * 会话保持类，用于下次请求保持cookie
 */
public class HttpSession {
    private HttpClientContext httpClientContext;

    public HttpSession() {
        CookieStore cookieStore = new BasicCookieStore();
        httpClientContext = HttpClientContext.create();
        httpClientContext.setCookieStore(cookieStore);
    }

    /**
     * 发送get请求；核心方法
     */
    public HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = HttpClientUtils.doGetHandle(url, headers, params, "", -1, true);
        return HttpClientUtils.getHttpClientResult(httpClient, httpGet, httpClientContext, false);
    }


    /**
     * 发送Post请求；核心方法
     */
    public HttpClientResult doPost(String url, Map<String, String> headers, Map<String, Object> params, RequestType requestType) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = HttpClientUtils.doPosthandle(url, headers, params, requestType, "", -1, true);
        return HttpClientUtils.getHttpClientResult(httpClient, httpPost, httpClientContext, false);
    }
}
